package cn.gogpay.duoim.sdk.service;

import cn.gogpay.duoim.sdk.constant.IMApis;
import cn.gogpay.duoim.sdk.constant.IMRespCode;
import cn.gogpay.duoim.sdk.exception.IMSDKException;
import cn.gogpay.duoim.sdk.model.IMRespResult;
import cn.gogpay.duoim.sdk.model.UserLoginReq;
import cn.gogpay.duoim.sdk.model.UserRegisterReq;
import cn.gogpay.duoim.sdk.model.UserTokenResp;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import okhttp3.Request;

/**
 * 认证
 */
public class IMAuthService {

    /**
     * 用户注册
     *
     * @param req 请求
     * @return 响应
     */
    public IMRespResult<UserTokenResp> userRegister(UserRegisterReq req) {
        req.setSecret(IMApiFactory.buildSecret());
        String params = JSON.toJSONString(req);
        Request request = IMApiFactory.buildRequest(params, IMApis.AUTH_USER_REGISTER);
        String data = IMApiFactory.callRequest(request);
        return parseTokenResp(data);
    }

    /**
     * 用户登录
     *
     * @param req 请求
     * @return 响应
     */
    public IMRespResult<UserTokenResp> userLogin(UserLoginReq req) {
        req.setSecret(IMApiFactory.buildSecret());
        String params = JSON.toJSONString(req);
        Request request = IMApiFactory.buildRequest(params, IMApis.AUTH_USER_TOKEN);
        String data = IMApiFactory.callRequest(request);
        return parseTokenResp(data);
    }

    private IMRespResult<UserTokenResp> parseTokenResp(String data) {
        TypeReference<IMRespResult<UserTokenResp>> typeReference = new TypeReference<IMRespResult<UserTokenResp>>() {
        };
        IMRespResult<UserTokenResp> result;
        try {
            result = JSON.parseObject(data, typeReference);
        } catch (Exception e) {
            throw new IMSDKException(IMRespCode.parse(), e.getMessage());
        }
        return result;
    }

}
